<?php
/**
 * Token.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-18
 * Time: 17:20
 */

namespace App\Tables;


use App\Tool\Crc32;
use App\Tool\RandomStr;

/**
 * Class Token
 * @package App\Tables
 */
class Token extends Base
{
    /**
     * 生成TOKEN
     * @param $uid
     * @param int $expTime
     * @return bool|string
     */
    public static function create($uid, $expTime = 86400)
    {
        $token = md5(md5(time()).md5(RandomStr::make()));
        $expTime += time();
        $find = self::where(['uid' => $uid])->first();
        $data = [
            'token' => $token,
            'token_crc32' => Crc32::get($token),
            'exp' => $expTime,
            'update_time' => time(),
        ];
        if(empty($find)) {
            $data['uid'] = $uid;
            $data['add_time'] = $data['update_time'];
            $ok = (bool) self::insertGetId($data);
        } else {
            $ok = (bool) self::where(['uid' => $uid])->update($data);
        }
        return $ok ? $token : false;
    }
}